﻿using DevExpress.Utils.Win;
using DevExpress.XtraEditors.Popup;
using DevExpress.XtraGrid.Demos.util;
using DevExpress.XtraGrid.Editors;
using DevExpress.XtraLayout;
using DXApplicationTangche.UC.下单MTO.Service;
using DXApplicationTangche.UC.订单一览新.辅料.service;
using DXApplicationTangche.UC.货号管理.service;
using DXApplicationTangche.UC.金蝶.dto;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DXApplicationTangche.UC.金蝶
{
    public partial class Form金蝶EBOM保存 : DevExpress.XtraEditors.XtraForm
    {
        private AccessoryKingDeeVO accessoryKingDeeVO选择辅料 = new AccessoryKingDeeVO();
        private List<AccessoryKingDeeVO> accessoryKingDee已选辅料list = new List<AccessoryKingDeeVO>();
        private List<AccessoryKingDeeDTO> 辅料一览 = new List<AccessoryKingDeeDTO>();
        private String fNumber面料 { get; set; }
        public String styleNameCN { get; set; }
        public String materialNo { get; set; }
        public String styleSizeCd { get; set; }

        public Form金蝶EBOM保存(String styleNameCN, String materialNo)
        {
            InitializeComponent();
            this.styleNameCN = styleNameCN;
            this.materialNo = materialNo;
            this.textBox款式名称.Text = styleNameCN;
            this.textBox面料号.Text = materialNo;
            //  面料
            KingDeeMaterialIntoDTO kingDeeMaterialIntoDTO = 货号管理Service.getKingDeeMaterialIntoDTO(materialNo);
            this.fNumber面料 = kingDeeMaterialIntoDTO.fnumber;
            //  辅料
            this.辅料一览 = 辅料Service.getAccessoryWithKingDeeInfoAll();
            this.searchLookUpEdit辅料一览.Properties.DataSource = this.辅料一览;
            //  尺码
            this.comboBox尺码组.Items.Clear();
            List<String> 尺码组 = new List<String>();
            尺码组 = MTO订单Service.findSizeCdByStyleNameCn(styleNameCN);
            foreach (String str in 尺码组)
            {
                this.comboBox尺码组.Items.Add(str);
            }
        }

        private void simpleButton添加辅料_Click(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(this.accessoryKingDeeVO选择辅料.fNumber))
            {
                if (!String.IsNullOrWhiteSpace(this.textBox数量.Text))
                {
                    try
                    {
                        this.accessoryKingDeeVO选择辅料.buildFFIXSCRAPQTY(Convert.ToDouble(this.textBox数量.Text.Trim()));
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        MessageBox.Show("请输入正确格式辅料固定损耗");
                        this.ActiveControl = this.textBox数量;
                        return;
                    }
                }
                else
                {
                    MessageBox.Show("请输入该辅料的固定损耗");
                    return;
                }
                if (this.accessoryKingDee已选辅料list.Count > 0)
                {
                    if (!this.accessoryKingDee已选辅料list.Exists(dto => dto.fNumber.Equals(this.accessoryKingDeeVO选择辅料.fNumber)))
                    {
                        this.accessoryKingDee已选辅料list.Add(this.accessoryKingDeeVO选择辅料);
                    }
                }
                else
                {
                    this.accessoryKingDee已选辅料list.Add(this.accessoryKingDeeVO选择辅料);
                }
            }
            this.gridControl子项物料一览.DataSource = this.accessoryKingDee已选辅料list;
            this.gridView子项物料一览.RefreshData();
            this.gridView子项物料一览.BestFitColumns();

        }
        #region
        private void searchLookUpEdit辅料一览_Popup(object sender, EventArgs e)
        {
            PopupSearchLookUpEditForm form = (sender as IPopupControl).PopupWindow as PopupSearchLookUpEditForm;
            SearchEditLookUpPopup popup = form.Controls.OfType<SearchEditLookUpPopup>().FirstOrDefault();
            LayoutControl layout = popup.Controls.OfType<LayoutControl>().FirstOrDefault();
            //如果窗体内空间没有确认按钮，则自定义确认simplebutton，取消simplebutton，选中结果label
            if (layout.Controls.OfType<Control>().Where(ct => ct.Name == "btOK").FirstOrDefault() == null)
            {
                //得到空的空间
                EmptySpaceItem a = layout.Items.Where(it => it.TypeName == "EmptySpaceItem").FirstOrDefault() as EmptySpaceItem;

                //得到取消按钮，重写点击事件
                Control clearBtn = layout.Controls.OfType<Control>().Where(ct => ct.Name == "btClear").FirstOrDefault();
                LayoutControlItem clearLCI = (LayoutControlItem)layout.GetItemByControl(clearBtn);
                clearBtn.Click += clear辅料一览Btn_Click;

                //添加一个simplebutton控件(确认按钮)
                LayoutControlItem myLCI = (LayoutControlItem)clearLCI.Owner.CreateLayoutItem(clearLCI.Parent);
                myLCI.TextVisible = false;
            }
        }
        private void searchLookUpEdit辅料一览View_Click(object sender, EventArgs e)
        {
            int[] a = this.searchLookUpEdit辅料一览.Properties.View.GetSelectedRows();
            if (a.Length > 0)
            {
                foreach (int rowHandle in a)
                {
                    String fNumber = this.searchLookUpEdit辅料一览.Properties.View.GetRowCellValue(rowHandle, "fNumber").ToString();
                    this.取单条数据(fNumber);
                }
            }
        }
        private void 取单条数据(String fNumber)
        {
            foreach (AccessoryKingDeeDTO item in this.辅料一览)
            {
                if (fNumber.Equals(item.fNumber))
                {
                    this.accessoryKingDeeVO选择辅料 = new AccessoryKingDeeVO(item);
                    break;
                }
            }
        }
        /// <summary>
        /// 清除按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void clear辅料一览Btn_Click(object sender, EventArgs e)
        {
            this.searchLookUpEdit辅料一览.ToolTip = null;
            searchLookUpEdit辅料一览.EditValue = null;
        }
        private void searchLookUpEdit辅料一览_CustomDisplayText(object sender, DevExpress.XtraEditors.Controls.CustomDisplayTextEventArgs e)
        {
            if (null != e.Value)
            {
                e.DisplayText = this.accessoryKingDeeVO选择辅料.subMaterialName;
            }
        }
        private void comboBox尺码组_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.styleSizeCd = "IGS_GROUP_SIZE-" + this.comboBox尺码组.Text.Trim();
        }
        #endregion

        private void simpleButton保存BOM_Click(object sender, EventArgs e)
        {
            //  尺码
            //  尺寸为空时默认M码
            if (String.IsNullOrWhiteSpace(this.styleSizeCd))
            {
                this.styleSizeCd = "IGS_GROUP_SIZE-M";
            }
            //  面料损耗
            List<ChildDTO> childDTOs = new List<ChildDTO>();
            if (!String.IsNullOrWhiteSpace(this.textBox面料固定损耗.Text))
            {
                try
                {
                    childDTOs.Add(new ChildDTO(this.fNumber面料, Convert.ToDouble(this.textBox面料固定损耗.Text.Trim())));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    MessageBox.Show("请输入正确格式面料固定损耗");
                    this.ActiveControl = this.textBox面料固定损耗;
                    return;
                }
            }
            else
            {
                MessageBox.Show("请填写面料固定损耗");
                return;
            }
            //  辅料损耗
            foreach (AccessoryKingDeeVO item in this.accessoryKingDee已选辅料list)
            {
                childDTOs.Add(new ChildDTO(item.fNumber, item.FFIXSCRAPQTY));
            }
            FunctionHelper.JsonSerialization(childDTOs);
            //判断样衣BOM是否存在,输入款号，物料号
            if (货号管理Service.sampleGarmentMaterialExited(styleNameCN, materialNo))
            {
                MessageBoxButtons messBtn = MessageBoxButtons.OKCancel;
                DialogResult dr = MessageBox.Show("样衣BOM已存在，是否继续保存？", "提示:确认", messBtn);
                if (dr != DialogResult.OK)
                {
                    return;
                }
            }
            try
            {
                if (String.IsNullOrEmpty(this.styleNameCN))
                {
                    MessageBox.Show("款式名称为空");
                    return;
                }
                if (String.IsNullOrEmpty(this.materialNo))
                {
                    MessageBox.Show("面料号为空");
                    return;
                }
                if (String.IsNullOrEmpty(this.styleSizeCd))
                {
                    MessageBox.Show("尺寸为空");
                    return;
                }
                //面料号清洗
                try { this.materialNo = this.materialNo.Replace("#", ""); } catch { }
                // saveEBOM
                // 根据金蝶EBOM保存返回值IsSuccess判断弹框显示
                //KindDeeApplyReturnDTO result =  货号管理Service.金蝶EBOM保存(this.styleNameCN, this.materialNo, this.styleSizeCd, childDTOs);
                //if (!result.IsSuccess)
                //{
                //    MessageBox.Show(result.SuccessMessages);
                //    return;
                //}
                String id = Regex.Replace(this.styleNameCN, " .*", "") + "_" + this.materialNo;
                货号管理Service.buildSaleSampleCreateBom(id);  
                MessageBox.Show("操作完成");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            this.Close();
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                String subMaterialCode = FunctionHelper.GetgridViewValue(
                                        this.gridView子项物料一览,
                                        this.gridView子项物料一览.FocusedRowHandle,
                                        "subMaterialCode");
                for (int i = this.accessoryKingDee已选辅料list.Count - 1; i >= 0; i--)
                {
                    if (subMaterialCode.Equals(this.accessoryKingDee已选辅料list[i].subMaterialCode))
                    {
                        this.accessoryKingDee已选辅料list.Remove(this.accessoryKingDee已选辅料list[i]);
                        break;
                    }
                }
                this.gridView子项物料一览.RefreshData();
            }
            catch { }
        }
    }
    public class AccessoryKingDeeVO
    {
        //  辅料类别
        public String subMaterialTypeId { get; set; }//辅料类别id
        public String subMaterialType { get; set; }//辅料类别

        //  辅料基础属性
        public String subMaterialSupplier { get; set; }//供应商
        public String subMaterialPicture { get; set; }//图片
        public String subMaterialNumber { get; set; }//品番（供应商编码）
        public String subMaterialCode { get; set; }//辅料编码
        public String subMaterialName { get; set; }//辅料名称
        public String subMaterialSpec { get; set; }//规格
        public String subMaterialSpecDesc { get; set; }//规格描述

        /*
         *  金蝶信息
         */
        public String fId { get; set; } //  金蝶物料主键
        public String fNumber { get; set; }  //    金蝶物料号
        public DateTime kingDeeSyncDate { get; set; }  //  金蝶同步时间
        public Double FFIXSCRAPQTY { get; set; }  //  
        public AccessoryKingDeeVO()
        {

        }

        public AccessoryKingDeeVO(SubMaterialSpuDao spuDao, SubMaterialSkuDTO skuDto)
        {
            this.subMaterialTypeId = spuDao.subMaterialTypeId;
            this.subMaterialType = spuDao.subMaterialType;
            this.subMaterialSupplier = spuDao.subMaterialSupplier;
            this.subMaterialCode = skuDto.subMaterialCode;
            this.subMaterialName = spuDao.subMaterialName;
            this.subMaterialSpec = skuDto.subMaterialSpec;
            this.subMaterialSpecDesc = skuDto.subMaterialSpec;
            this.fId = skuDto.fId;
            this.fNumber = skuDto.fNumber;
            this.kingDeeSyncDate = skuDto.kingDeeSyncDate;
        }

        public AccessoryKingDeeVO(AccessoryKingDeeDTO dto)
        {
            this.subMaterialTypeId = dto.subMaterialTypeId;
            this.subMaterialType = dto.subMaterialType;
            this.subMaterialSupplier = dto.subMaterialSupplier;
            this.subMaterialPicture = dto.subMaterialPicture;
            this.subMaterialNumber = dto.subMaterialNumber;
            this.subMaterialCode = dto.subMaterialCode;
            this.subMaterialName = dto.subMaterialName;
            this.subMaterialSpec = dto.subMaterialSpec;
            this.subMaterialSpecDesc = dto.subMaterialSpecDesc;
            this.fId = dto.fId;
            this.fNumber = dto.fNumber;
            this.kingDeeSyncDate = dto.kingDeeSyncDate;
        }
        public AccessoryKingDeeVO buildFFIXSCRAPQTY(Double FFIXSCRAPQTY)
        {
            this.FFIXSCRAPQTY = FFIXSCRAPQTY;
            return this;
        }
    }
}
